var api = require('../config/api.js');
var app = getApp();

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 封封微信的的request
 */
function request(url, data = {}, method = "GET") {
  return new Promise(function(resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json',
        'X-Litemall-Token': wx.getStorageSync('token')
      },
      success: function(res) {

        if (res.statusCode == 200) {

          if (res.data.errno == 501) {
            // 清除登录相关内容
            try {
              wx.removeStorageSync('userInfo');
              wx.removeStorageSync('token');
            } catch (e) {
              // Do something when catch error
            }
            // 切换到登录页面
            wx.navigateTo({
              url: '/pages/auth/login/login'
            });
          } else {
            resolve(res.data);
          }
        } else {
          reject(res.errMsg);
        }

      },
      fail: function(err) {
        reject(err)
      }
    })
  });
}

function redirect(url) {

  //判断页面是否需要登录
  if (false) {
    wx.redirectTo({
      url: '/pages/auth/login/login'
    });
    return false;
  } else {
    wx.redirectTo({
      url: url
    });
  }
}

function showErrorToast(msg) {
  wx.showToast({
    title: msg,
    image: '/static/images/icon_error.png'
  })
}

// 保存图片
function saveImage(imageTempPath) {
  wx.getSetting({
    complete(res) {
      console.log("授权信息：", res.authSetting);
      // 已授权
      if (res.authSetting['scope.writePhotosAlbum']) {
        console.log("是否已经授权:", res.authSetting['scope.writePhotosAlbum']);
        downloadImage(imageTempPath);
      } else {
        // 拒绝授权
        wx.authorize({
          scope: 'scope.writePhotosAlbum',
        }).then(() => {
          downloadImage(imageTempPath);
        }).catch(() => {
          wx.showModal({
            title: '您未开启保存图片或视频的权限',
            content: '为了给您提供更好的服务，请您授权权限',
            success: res2 => {
              if (res2.confirm) {
                wx.openSetting({
                  success(res) {
                    console.log('打开设置页', res.authSetting);
                  }
                })
              } else {
                console.log('再次拒绝')
              }
            }
          })
        });
      }
    }
  })
}

// 保存图片
function downloadImage(imageTempPath) {
  wx.getImageInfo({
    src: imageTempPath,
    success(result) {
      console.log(result);
      wx.showLoading({ title: '保存中...'})
      if (result.path) {
        wx.saveImageToPhotosAlbum({
          filePath: result.path,
        }).then((getImageInfoResult) => {
          wx.hideLoading()
          if (getImageInfoResult.errMsg === 'saveImageToPhotosAlbum:ok') {
            wx.showToast({
              title: "已成功保存至相册！",
              duration: 1000
            })
          } else {
            wx.showToast({
              title: "图片保存失败！",
              duration: 1000
            })
          }
        }).catch(() => {
          wx.hideLoading()
        })
      }
    },
    fail(error) {
      console.log('error11', error);
    },
  });
}

module.exports = {
  formatTime,
  request,
  redirect,
  showErrorToast,
  saveImage
}